<?php

declare(strict_types=1);

namespace app\controller\system;

use app\BaseController;
use app\model\AuthPermission;
use app\service\factory\ResponseFactory;
use app\service\sys\PermissionService;
use app\validate\system\SysPermissionValidate;
use InvalidArgumentException;
use think\Response;
use Throwable;

class Permission extends BaseController
{
    public function index(PermissionService $permissionService): Response
    {
        try {
            $page = max(1, (int) $this->request->param('page', 1));
            $pageSize = (int) $this->request->param('page_size', 50);
            $pageSize = $pageSize > 0 ? min($pageSize, 200) : 50;

            $filters = $this->request->only([
                'keyword',
                'client_type',
                'status',
            ], 'get');

            $paginator = $permissionService->paginate($filters, $page, $pageSize);
            $list = $permissionService->formatCollection($paginator->items());

            return json(ResponseFactory::paginated(
                $list,
                (int) $paginator->total(),
                $page,
                $pageSize
            ));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function read(int $id, PermissionService $permissionService): Response
    {
        try {
            $permission = $permissionService->findById($id);
            if (!$permission) {
                return json(ResponseFactory::error('权限不存在', 404));
            }

            return json(ResponseFactory::success($permissionService->format($permission)));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function save(PermissionService $permissionService): Response
    {
        try {
            $payload = $this->request->only([
                'name',
                'code',
                'description',
                'client_type',
                'status',
                'role_ids',
            ], 'post');

            $this->validate($payload, SysPermissionValidate::class . '.create');

            $permission = $permissionService->create($payload);

            return json(ResponseFactory::success($permissionService->format($permission), '权限已创建'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function update(int $id, PermissionService $permissionService): Response
    {
        try {
            $permission = AuthPermission::find($id);
            if (!$permission) {
                return json(ResponseFactory::error('权限不存在', 404));
            }

            $payload = $this->request->only([
                'name',
                'code',
                'description',
                'client_type',
                'status',
                'role_ids',
            ], 'put');
            $payload['id'] = $id;

            $this->validate($payload, SysPermissionValidate::class . '.update');

            $updated = $permissionService->update($permission, $payload);

            return json(ResponseFactory::success($permissionService->format($updated), '权限已更新'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function delete(int $id, PermissionService $permissionService): Response
    {
        try {
            $permission = AuthPermission::find($id);
            if (!$permission) {
                return json(ResponseFactory::error('权限不存在', 404));
            }

            if (!$permissionService->delete($permission)) {
                return json(ResponseFactory::error('删除失败', 500));
            }

            return json(ResponseFactory::success(true, '权限已删除'));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }
}
